# coding:utf-8

from src.config.oracle_config import OracleConfig
from src.manager.html_manager import HtmlManager
from src.manager.log_manager import LogManager
from src.manager.oracle_manager import OracleManager

Logger = LogManager.get_logger(__name__)


class EtfTransactionDataHandler:
    """
    etf_transaction_data表的处理器
    """

    def __init__(self):
        """
        构造函数，初始化oracle_manager和cursor对象
        """
        self.oracle_manager = OracleManager(OracleConfig.Username, OracleConfig.Password, OracleConfig.Url)
        self.oracle_manager.connect()
        self.cursor = self.oracle_manager.get_cursor()

    def update_last_close_price_by_date_and_code(self):
        """
        调用接口，根据date和code，更新last_close_price字段
        """
        Logger.info('调用接口，根据date和code，更新last_close_price字段')

        # 查找code_，并去重
        self.cursor.execute(
            "select distinct t.code_ from etf_transaction_data t")
        etf_code_list = self.cursor.fetchall()
        if len(etf_code_list) != 0:
            for etf_code in etf_code_list:

                # 根据code_查找etf_transaction_data记录
                self.cursor.execute(
                    "select * from etf_transaction_data t where t.code_=" + etf_code[0] + " order by t.date_ asc")
                etf_transaction_data_list = self.cursor.fetchall()

                # 查找前一个交易日的收盘价，并更新当前交易日的last_close_price字段
                first_record = True
                last_close_price = None
                for etf_transaction_data in etf_transaction_data_list:
                    if first_record:
                        last_close_price = etf_transaction_data[4]
                        first_record = False
                        continue
                    else:
                        date_ = etf_transaction_data[1].strftime("%Y-%m-%d")
                        sql = "update etf_transaction_data t set t.last_close_price=" + str(
                            last_close_price) + " where t.code_=" + etf_transaction_data[
                                  2] + " and t.date_=to_date('" + date_ + "', 'yyyy-mm-dd')"
                        # 根据code_和date_，更新last_close_price
                        self.cursor.execute(sql)
                        self.oracle_manager.conn.commit()
                        last_close_price = etf_transaction_data[4]
        else:
            Logger.warn('code_字段为空')
